package com.own.demo.lwf.utils.javaUtils;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author liwenfeng
 * @Description jwt工具类
 * @Date 2023/07/07/15:56
 * @Version 1.0
 */
public class JwtUtils {
    public static final long EXPIRATION = 1000 * 60 * 60 * 24;
    public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 根据用户id和nickname生成一个token
     *
     * @param id
     * @param nickname
     * @return
     */
    public static String getToken(String id, String nickname) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("online-encourage")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .claim("id", id)
                .claim("nickname", nickname)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 判断token是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        Date expiration = getClaimByToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static Claims getClaimByToken(String token) {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 获取token并解析--得到用户id
     *
     * @param request
     * @return
     */
    public static String getUserIdByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("token为：--->>>>>>>>>>>>>>" + token);
        if (StringUtils.isEmpty(token)) {
            return "";
        }
        return (String) getClaimByToken(token).get("id");
    }
}
